package com.leaf.u.basehttp.http;

import com.leaf.u.basehttp.download.Headers;
import com.leaf.u.basehttp.http.inter.ILeafRequest;
import com.leaf.u.basehttp.http.inter.RequestInterceptor;
import com.leaf.u.basehttp.http.response.LeafResponse;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by bz on 2017/5/25.
 */

public class HttpEngine {
    private OkHttpClient client;
    private Dispatcher dispatcher;
    private List<RequestInterceptor> interceptors = new ArrayList<>();

    public List<RequestInterceptor> interceptors() {
        return this.interceptors;
    }

    public void addInterceptor(RequestInterceptor interceptor) {
        this.interceptors.add(interceptor);
    }

    public HttpEngine(OkHttpClient client) {
        if (client != null) {
            this.client = client;
        } else {
            this.client = new OkHttpClient.Builder().build();
        }
        dispatcher = new Dispatcher();
    }

    public Dispatcher dispatcher() {
        return dispatcher;
    }

    public LeafResponse async_request(ILeafRequest<Request> leafRequest) throws IOException {
        Request request = leafRequest.build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            Headers.Builder builder = new Headers.Builder();
            okhttp3.Headers okheaders = response.headers();
            Set<String> names = okheaders.names();
            Iterator<String> iterator = names.iterator();
            while (iterator.hasNext()) {
                String name = iterator.next();
                String value = okheaders.get(name);
                builder.add(name, value);
            }
            Headers headers = builder.build();
            LeafResponse leafResponse = new LeafResponse.Builder()
                    .setCode(response.code())
                    .setContentLength(response.body().contentLength())
                    .setHeaders(headers)
                    .setInputStream(response.body().byteStream())
                    .build();
            return leafResponse;
        } finally {

        }
    }
}
